//
//  HKLogManager.m
//  HKMacros
//
//  Created by 胡锦涛 on 2020/7/4.
//

#import "HKLogManager.h"
#import "HKMacro.h"
//网络
#import "HKReachability.h"
#import "NSArray+HKExtension.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

NSString *const HK_USERACTION = @"HK_USERACTION";
@interface HKLogManager()
/** 本条日志的客户端序号 */
@property (nonatomic, assign) NSInteger  logIdx ;
/** 本条日志的客户端生成时间 */
@property (nonatomic, strong) NSString * logTime ;
/** 客户端类型ID */
@property (nonatomic, strong) NSString * clientId ;
/** 客户端版本号 */
@property (nonatomic, strong) NSString * clientVersion ;
/** 日志组件版本号 */
@property (nonatomic, strong) NSString * logVersion ;
/** 客户端唯一ID UUID*/
@property (nonatomic, strong) NSString * deviceId ;
/** 会话ID 唯一追踪本次全流程业务如：CertifyID */
@property (nonatomic, strong) NSString * sessionId ;
/** 日志事件名称 */
@property (nonatomic, strong) NSString * actionName ;
/** 日志等级 */
@property (nonatomic, assign) HKLogLevel logLevel ;
/** 业务参数 */
@property (nonatomic, strong) NSDictionary * bizParam ;
/** 设备机型简要信息 */
@property (nonatomic, strong) NSString * phonePrint ;
/** 设备系统版本号 */
@property (nonatomic, strong) NSString * osVersion ;
/** 设备网络类型 */
@property (nonatomic, strong) NSString * netType ;
/** 设备分辨率 */
@property (nonatomic, strong) NSString * screenMetrix ;
@end
@implementation HKLogManager

+ (instancetype)shared {
    static HKLogManager *_sharedSingleton = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //不能再使用alloc方法
        //因为已经重写了allocWithZone方法，所以这里要调用父类的分配空间的方法
        _sharedSingleton = [[super allocWithZone:NULL] init];
    });
    return _sharedSingleton;
}
// 防止外部调用alloc 或者 new
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [HKLogManager shared];
}

+ (void)logWithSessionId:(NSString*)sessionId actionName:(NSString*)actionName logLevel:(HKLogLevel)logLevel bizParam:(NSMutableDictionary*)bizParam{
    [[HKLogManager shared] HKLogWithSessionId:sessionId actionName:actionName logLevel:logLevel bizParam:bizParam];
}
+ (void)logWithSessionId:(NSString*)sessionId actionName:(NSString*)actionName bizParam:(NSMutableDictionary*)bizParam{
    [[HKLogManager shared] HKLogWithSessionId:sessionId actionName:actionName logLevel:HKLogLevelInfo bizParam:bizParam];
}
+ (void)reportLog {
    NSArray * dataArray = [[NSUserDefaults standardUserDefaults] objectForKey:HK_USERACTION];
    
    if (dataArray != nil && dataArray.count > 0) {
        HKLog(@"统计数据来了：%@",[dataArray hk_arrayToJSONString]);
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:HK_USERACTION];
        [HKLogManager shared].logIdx = 0;
    }
}

- (void)HKLogWithSessionId:(NSString*)sessionId actionName:(NSString*)actionName logLevel:(HKLogLevel)logLevel bizParam:(NSMutableDictionary*)bizParam{
    
    if (!self.logIdx) {
        self.logIdx = 0;
    }
    self.logIdx ++;
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    self.logTime = [dateformatter stringFromDate:[NSDate date]];
    self.clientId = @"iOS";
    self.clientVersion = HKShortVersion;
    self.logVersion = @"1.0";
    self.deviceId = [[UIDevice currentDevice]identifierForVendor].UUIDString;
    // 流程唯一ID
    self.sessionId = sessionId ? sessionId : @"";
    // 小流程(Start End)
    self.actionName = actionName ? actionName : @"" ;
    // 日志等级
    self.logLevel = logLevel;
    NSString * logLevelType = [self getLogLevelType:logLevel];
    // 胡锦涛的 iPhone,iOS,12.4
    self.phonePrint = [NSString stringWithFormat:@"%@,%@,%@",HKDeviceName,HKDeviceSystemName,HKDeviceSystemVersion];
    // 12.4
    self.osVersion = HKDeviceSystemVersion;
    // 网络类型
    self.netType = [self getNetConnectType];
    // 设备分辨率
    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat width = [UIScreen mainScreen].bounds.size.width*scale;
    CGFloat height = [UIScreen mainScreen].bounds.size.height*scale;
    self.screenMetrix = [NSString stringWithFormat:@"%.fx%.f",width,height];
    
    NSDictionary  *logDic = @{
        @"logIdx": @(self.logIdx),
        @"logTime": self.logTime,
        @"clientId" : self.clientId,
        @"clientVersion" : self.clientVersion,
        @"logVersion" : self.logVersion,
        @"deviceId" : self.deviceId,
        @"sessionId" : self.sessionId,
        @"actionName" : self.actionName,
        @"logLevel" : logLevelType,
        @"bizParam" : bizParam != nil ? bizParam : @"",
        @"phonePrint" : self.phonePrint,
        @"osVersion" : self.osVersion,
        @"netType" : self.netType,
        @"screenMetrix" : self.screenMetrix
    };
    NSArray * dataArray =  [[NSUserDefaults standardUserDefaults] objectForKey:HK_USERACTION];
    NSMutableArray * tempArray = @[].mutableCopy;
    if (dataArray.count) {
        tempArray = dataArray.mutableCopy;
    }
    [tempArray addObject:logDic];
    [[NSUserDefaults standardUserDefaults] setObject:tempArray forKey:HK_USERACTION];
    
}
+ (HKLogLevel)getLogLevel {
    return [HKLogManager shared].logLevel;
}
+ (NSString *)getLogLevelType {
    return [[HKLogManager shared] getLogLevelType:[[HKLogManager shared] logLevel]];
}

- (NSString *)getLogLevelType:(HKLogLevel)logLevel {
    switch (logLevel) {
        case HKLogLevelError:
            return @"[ERROR]--->";
            break;
        case HKLogLevelInfo:
            return @"[INFO]--->";
            break;
            
        case HKLogLevelDebug:
            return @"[DEBUG]--->";
            break;
            
        case HKLogLevelVerbose:
            return @"[VBOSE]--->";
            break;
            
        case HKLogLevelWarning:
            return @"[WARNING]--->";
            break;
            
        default:
            return @"[VBOSE]--->";
            break;
    }
}
+ (NSString *)getNetConnectType {
    return [[HKLogManager shared] getNetConnectType];
}
- (NSString *)getNetConnectType{
    
    NSString *netconnType = @"";
    
    HKReachability *reach = [HKReachability reachabilityWithHostName:@"www.apple.com"];
    
    switch ([reach currentReachabilityStatus]) {
        case HKNetworkStatusNotReachable:// 没有网络
        {
            netconnType = @"NoNetwork";
        }
            break;
            
        case HKNetworkStatusReachableViaWiFi:// Wifi
        {
            netconnType = @"Wifi";
        }
            break;
            
        case HKNetworkStatusReachableViaWWAN:// 手机自带网络
        {
            // 获取手机网络类型
            CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
            
            if (@available(iOS 12.0, *)) {
                // iOS 12.0 以上
                NSString *currentStatus = info.serviceCurrentRadioAccessTechnology;
                
                if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
                    
                    netconnType = @"GPRS";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
                    
                    netconnType = @"2.75G EDGE";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
                    
                    netconnType = @"3.5G HSDPA";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
                    
                    netconnType = @"3.5G HSUPA";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
                    
                    netconnType = @"2G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
                    
                    netconnType = @"HRPD";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
                    
                    netconnType = @"4G";
                }
            } else {
                
                // iOS 12.0 以下
                NSString *currentStatus = info.currentRadioAccessTechnology;
                
                if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyGPRS"]) {
                    
                    netconnType = @"GPRS";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyEdge"]) {
                    
                    netconnType = @"2.75G EDGE";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyWCDMA"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSDPA"]){
                    
                    netconnType = @"3.5G HSDPA";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyHSUPA"]){
                    
                    netconnType = @"3.5G HSUPA";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMA1x"]){
                    
                    netconnType = @"2G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORev0"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevA"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyCDMAEVDORevB"]){
                    
                    netconnType = @"3G";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyeHRPD"]){
                    
                    netconnType = @"HRPD";
                }else if ([currentStatus isEqualToString:@"CTRadioAccessTechnologyLTE"]){
                    
                    netconnType = @"4G";
                }
            }
        }
            break;
            
        default:
            break;
    }
    
    return netconnType;
}
@end
